package com.myna.csv.extractor;

import com.myna.csv.domain.PropertyStr;
import com.myna.csv.domain.RDCEntity;
import com.myna.csv.domain.RDCProperty;
import com.myna.csv.utils.DateUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.myna.csv.initial.InitialProcessor.*;

public class AllFilesEntityExtract extends PublicExtractor {
    public static final Logger LOGGER = LogManager.getLogger(AllFilesEntityExtract.class);

    private static List<Long> underlyingPI = new ArrayList<>();
    private static List<Long> bodyGroupPI = new ArrayList<>();

//    public static File underlyingPIFile = null;
//    public static File bodyGroupPIFile = null;
//    String zip_ISINName = PropertyStr.ISINName + "-" + dateStr + ".zip";
//    private File iSINFile = null;
//    private static String dateStr;

    public void extract(File file) {
        try (InputStream inputStream = new FileInputStream(file)) {
            XMLStreamReader reader1 = openXmlStreamReader(inputStream);
            Boolean flag = isInstrument(reader1);

            //close connection
            closeStream(xmlStreamReader, gis, reader1, inputStream);

            if (flag) {
                try (InputStream inputStream1 = new FileInputStream(file)) {
                    XMLStreamReader reader = openXmlStreamReader(inputStream1);
                    doExacter(reader);

                    closeStream(xmlStreamReader, gis, reader, inputStream1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doExacter(XMLStreamReader reader) throws XMLStreamException {
//        try {
//            dateStr = DateUtils.formatDate(new Date(), PropertyStr.dateCS_timestampFormat);
//        } catch (ParseException e) {
//            LOGGER.info(e);
//        }

//        String ISINName = PropertyStr.ISINName + "-" + dateStr + ".csv";
//        String underlyingFileName = PropertyStr.underlyingPIFileName + "-" + dateStr + ".csv";
//        String bodyGroupFileName = PropertyStr.bodyGroupPIFileName + "-" + dateStr + ".csv";
//        underlyingPIFile = setFileTitle(rdcFilePIPath, underlyingFileName);
//        bodyGroupPIFile = setFileTitle(rdcFilePIPath, bodyGroupFileName);
//        iSINFile = setFileTitle(rdcFilePath, ISINName);

        while (reader.hasNext()) {
            int eventType = reader.next();
            if (XMLStreamConstants.START_ELEMENT == eventType) {
                String localName = reader.getLocalName();
                if ("entity".equals(localName)) {
                    RDCEntity rdcEntity = new RDCEntity();
                    readRDCEntity(rdcEntity, reader);

                    //subtype="EIW"的entity范围中
                    if (category_list.contains(rdcEntity.getSubtype())) {
                        //get underlying and bodyGroup(issue)
                        writeRDCEntityIntoFile(rdcEntity);
                    }
                    try {
                        List<RDCProperty> rdcProperties = rdcEntity.getRdcProperties();
                        if (rdcProperties.size() <= 0) {
                            return;
                        }
                        for (int i = 0; i < rdcProperties.size(); i++) {
                            RDCProperty rdcProperty = rdcProperties.get(i);

                            //get all stubISIN(没有subtype="EIW"范围的限制)
                            if (rdcProperty.getProperty_id() == 27229L && rdcProperty.getValid_to_inc_time() == null) {
                                //把rdcEntity.getPi()和rdcEntity写入ISIN文件中
                                writeToCSVFile(rdcEntity.getPi(), rdcEntity, PropertyStr.iSINFlag);
//                                zipFile(iSINFile, zip_ISINName);
//                                delFile(iSINFile);
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("The Pi is exist, The pi is : " + rdcEntity.getPi() + e);
                    }
                }
            }
        }
    }

    //Extractor RDCProperty
    public void readRDCProperty(XMLStreamReader reader, RDCProperty property) throws XMLStreamException {
        while (reader.hasNext()) {
            int eventType = reader.next();
            String localName;
            switch (eventType) {
                case XMLStreamConstants.END_ELEMENT:
                    localName = reader.getLocalName();
                    if ("content".equals(localName)) {
                        return;
                    }
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    localName = reader.getLocalName();
                    if ("property".equals(localName)) {
                        property = new RDCProperty();
                        String propertyId = reader.getAttributeValue(null, "id");
                        property.setProperty_id(Long.valueOf(propertyId));
                        property.setProperty_name(jsonMappingMap.get(Long.valueOf(propertyId)));
                        readRDCPropertyName(reader, property);

                        if (needed_pi_properIds_List.contains(propertyId)) {
                            properties.add(property);
                        }
                    }
                    break;
            }
        }
    }

    public void writeRDCEntityIntoFile(RDCEntity rdcEntity) {
        Long PI = -1L;
        try {
            List<RDCProperty> rdcProperties = rdcEntity.getRdcProperties();
            if (rdcProperties.size() > 0) {
                for (int i = 0; i < rdcProperties.size(); i++) {
                    RDCProperty rdcProperty = rdcProperties.get(i);
                    if (rdcProperty.getProperty_id() == 135653L || rdcProperty.getProperty_id() == 27325L) {
                        //get Underying Asset PI and basket underlying asset pi
                        PI = Long.valueOf(rdcProperty.getCurrValue());
                        if (!underlyingPI.contains(PI)) {
                            underlyingPI.add(PI);
                            //根据PI到Underlying文件中查询PI是否存在，如不存在，则写入文件中，格式为PI,rdcEntity
                            writeToCSVFile(PI, null, PropertyStr.underlyingPIFlag);
                        }
                    } else if (rdcProperty.getProperty_id() == 27233L) {
                        //get bodyGroup
                        PI = Long.valueOf(rdcProperty.getCurrValue());
                        if (!bodyGroupPI.contains(PI)) {
                            bodyGroupPI.add(PI);
                            //根据PI到bodyGroup文件中查询PI是否存在，如不存在，则写入文件中，格式为PI,rdcEntity
                            writeToCSVFile(PI, null, PropertyStr.bodyGroupPIFlag);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("The PI is exist,and it's :" + rdcEntity.getPi() + e);

        }
    }
}


